﻿var ipRegEx = /^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$/;
var posIntRegEx = /^\d+$/;


Settings = (function () {
    this.receiver;
    this.host;
    this.user;
    this.password;
    this.port;
    this.params;
    this.ssl = 'off';
    this.isActive='off';
});

SettingsHelper= (function () {
    var getSettings = {
        SettingsLoded: function (value) {
            try {
                var result = false;
                if (sessionStorage)
                    if (value)
                        sessionStorage.setItem('settingsLoded', value);
                    else if (sessionStorage.getItem('settingsLoded') != null) {
                        result = JSON.parse(sessionStorage.getItem('settingsLoded'));
                }

                return result;
            }
            catch (err) { alert(err.message); };
        },
        SetupSettings: function (settingsArr) {
            try{
                var settingsList = [];
                for (var i = 0; i < settingsArr.length; i++)
                {
                    settingsList.push(settingsArr[i]);
                }
                sessionStorage.setItem('settingsList', JSON.stringify(settingsList));
                console.log('set: ' + JSON.stringify(settingsList));
                SettingsHelper.ActiveSettings(true);

            }
            catch (err) { alert(err.message); };
        },

        SettingsList: function () {
            var result = [];
            if (sessionStorage && sessionStorage.getItem('settingsList') != null) {
                result = JSON.parse(sessionStorage.getItem('settingsList'));
            }
            console.log('get: ' + JSON.stringify(result));

            return result;
        },
        GetSettingsByReceiver:function(receiver)
        {
            var result = SQLike.q(
               {
                   Select: ['*'],
                   From: SettingsHelper.SettingsList(),
                   Where: function () { return this.receiver == receiver }
               });

            return result;
        },
        GetSettingsActive:function()
        {
            var result = SQLike.q(
               {
                   Select: ['*'],
                   From: SettingsHelper.SettingsList(),
                   Where: function () { return this.isActive == 'on' }
               });

            return result;
        },
        GetSettingsActiveExcluding:function(receiver)
        {
            var result = SQLike.q(
               {
                   Select: ['*'],
                   From: SettingsHelper.SettingsList(),
                   Where: function () { return this.isActive == 'on' && this.receiver != receiver }
               });

            return result;
        },
        GetUserAccountForURI: function (settings) {
            var result = '';

            var active = SettingsHelper.ActiveSettings();
            if (!settings)
                settings = active;

            if (settings)
                result = 'http://' + (settings.user == '' ? '' : settings.user + ':' + settings.password + '@') + settings.host;

            return result;
        },
        ActiveSettings: function (value) {
            try {
                var result = {};
                if (sessionStorage)
                    if (value) {
                        var active = SettingsHelper.GetSettingsActive();                        
                        if (active.length > 0) {
                            sessionStorage.setItem('activeSettings', JSON.stringify(active[0]));
                        }
                    }
                    else if (sessionStorage.getItem('activeSettings') != null) {
                        result = JSON.parse(sessionStorage.getItem('activeSettings'));
                    }
                return result;
            }
            catch (err) { alert(err.message); };
        },
        DeleteSettings: function (setttingID) {
            var settings = SettingsHelper.SettingsList();

            for (var i = 0; i < settings.length; i++)
            {
                if (settings[i].receiver == setttingID) {
                    settings.splice(i, 1);
                    break;
                }
            }
            SettingsHelper.SetupSettings(settings);
            window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onSuccessW, fail);
        },
        isValid: function (settingsItem, orReceiver)
        {
            var isValid = true;
            $('#activeProfileValidate').text('');
            $('#receiverValidate').text('');
            $('#hostValidate').text('');
            $('#userValidate').text('');
            $('#passwordValidate').text('');
            $('#portValidate').text('');
            $('#paramsValidate').text('');

            //## Receiver Rules ##//
            if (settingsItem.receiver.length == 0) {
                $('#receiverValidate').text('Receiver name cannot be empty');
                isValid = false;
            } else if (settingsItem.receiver.length > 20) {
                $('#receiverValidate').text('Receiver name cannot be more than 20 letters');
                isValid = false;
            } else if (settingsItem.receiver != orReceiver && SettingsHelper.GetSettingsByReceiver(settingsItem.receiver).length > 0) {
                $('#receiverValidate').text('Receiver name must be unique. Choose another name');
                isValid = false;
            }
            //## End Receiver Rules ##//

            //## Host Rules ##//
            if (settingsItem.host.length == 0) {
                $('#hostValidate').text('Host number cannot be empty');
                isValid = false;
            } else if (ipRegEx.exec(settingsItem.host) == null) {
                $('#hostValidate').text('Host must be a valid ip address');
                isValid = false;
            }
            //## End Host Rules ##//
            
            //## Port Rules ##//
            if (settingsItem.port.length > 0 &&
                (posIntRegEx.exec(settingsItem.port) == null || settingsItem.port > 65535)) {
                $('#portValidate').text('Port must be a positive number and between 1 and 65535');
                isValid = false;
            }
            //## End Port Rules ##//

            //## Active Rules ##//
            var activeProfile = SettingsHelper.GetSettingsActiveExcluding(settingsItem.receiver);
            //if (settingsItem.isActive == 'off' && activeProfile.length == 0) {
            //    $('#activeProfileValidate').text('There is no active profile. Please activate this one and test the connection');
            //    isValid = false;
        //} 
        if (settingsItem.isActive == 'on' && activeProfile.length > 0) {
                $('#activeProfileValidate').text(activeProfile[0].receiver + ' profile is active. You must deactivate it first.');
                isValid = false;
            }
            //## End Active Rules ##//
            
            return isValid;
        },
    };


    return getSettings;
 })();
